import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'product_content/product.dart';
import 'product_content/description.dart';
import 'product_content/comment.dart';
import 'product_content/recommend.dart';
import 'product_content/product_bottom.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../utils/dio_util.dart';
import '../widget/my_loading.dart';
import '../widget/my_image.dart';
import '../widget/product_content_page_indicator.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
double getY(BuildContext buildContext) {
  final RenderBox box = buildContext.findRenderObject();
  final size = box.size;
  print(size);
  final topLeftPosition = box.localToGlobal(Offset.zero);
  return topLeftPosition.dy;
}

class ProductContentPage extends StatefulWidget {
  final Map arguments;

  ProductContentPage({Key key, this.arguments}) : super(key: key);

  _ProductContentPageState createState() => _ProductContentPageState();
}

class _ProductContentPageState extends State<ProductContentPage>
    with TickerProviderStateMixin {
  Map<String, dynamic> productContentInfo = {};
  Map<String, dynamic> product; //产品详情
  Map<String, dynamic> reply; //评论
  List<dynamic> productValue; //产品属性
  List<dynamic> recommendProducts; //推荐
  int collect; //是否收藏
  Map<String, dynamic> description; //产品详情
  bool isLoaded = false;
  TabController _tabController;
  var tabs = <Tab>[
    Tab(
      text: "商品",
    ),
    Tab(
      text: "评价",
    ),
    Tab(
      text: "推荐",
    ),
    Tab(
      text: "详情",
    )
  ];
  ScrollController _scrollController = ScrollController();
  bool showToTopBtn = false; //是否显示“返回到顶部”按钮
  GlobalKey globalKeySp = GlobalKey(); //商品
  GlobalKey globalKeyPj = GlobalKey(); //评价
  GlobalKey globalKeyTj = GlobalKey(); //推荐
  GlobalKey globalKeyXq = GlobalKey(); //详情
  var spY = 0.0;
  var pjY = 0.0;
  var tjY = 0.0;
  var xqY = 0.0;

  @override
  void initState() {
    super.initState();
    _getContentData();

    _tabController =
        TabController(initialIndex: 0, length: tabs.length, vsync: this);
    _scrollController.addListener(() {
      var of = _scrollController.offset;
      WidgetsBinding.instance.addPostFrameCallback((callback) {
        spY = getY(globalKeySp.currentContext);
        pjY = getY(globalKeyPj.currentContext);
        tjY = getY(globalKeyTj.currentContext);
        xqY = getY(globalKeyXq.currentContext);
        if (of > xqY - spY) {
          _tabController.animateTo(3);
        } else if (of > pjY - spY) {
          _tabController.animateTo(2);
        } else if (of > tjY - spY) {
          _tabController.animateTo(1);
        } else {
          _tabController.animateTo(0);
        }
      });
    });
  }

  void _getContentData() async {
    var api = '/api/mall/product/info.service';
    print('productId1:${widget.arguments['productId']}');
    Map<String, int> param = {'productId': widget.arguments['productId']};
    DioUtil dio = DioUtil();
    var res = await dio.get(api, data: param);
    if (res['code'] == 200) {
      var result = res['result'];
      print(result);
      setState(() {
        product = result['product'];
        reply = result['reply'];
        productValue = result['productValue'];
        recommendProducts = result['recommendProducts'];
        collect = result['collect'];
        description = result['description'] == ''
            ? {'description': ''}
            : result['description'];
        isLoaded = true;
      });
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (isLoaded) {
      return Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Opacity(
              opacity: 1,
              child: Container(
                color: Colors.white,
                child: AppBar(
                  backgroundColor: Colors.white,
                  title: TabBar(
                    isScrollable: false,
                    onTap: (int index) {
                      switch (index) {
                        case 0:
                          _scrollController.jumpTo(0);
                          _tabController.animateTo(0);
                          break;
                        case 1:
                          _scrollController.jumpTo(pjY - spY);
                          _tabController.animateTo(1);
                          break;
                        case 2:
                          _scrollController.jumpTo(tjY - spY);
                          _tabController.animateTo(2);
                          break;
                        case 3:
                          _scrollController.jumpTo(xqY - spY);
                          _tabController.animateTo(2);
                          break;
                      }
                    },
                    tabs: tabs,
                    controller: _tabController,
                    indicatorColor: Colors.red,
                    indicatorSize: TabBarIndicatorSize.label,
                    labelColor: Colors.black87,
                    labelStyle:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),
                    unselectedLabelColor: Colors.red,
                    unselectedLabelStyle: TextStyle(
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ),
            Expanded(
              child: NotificationListener(
                onNotification: (scrollNotification) {
                  if (scrollNotification is ScrollUpdateNotification) {
                    if (scrollNotification.metrics.pixels < 100 &&
                        showToTopBtn) {
                      setState(() {
                        showToTopBtn = false;
                      });
                    } else if (scrollNotification.metrics.pixels >= 100 &&
                        showToTopBtn == false) {
                      setState(() {
                        showToTopBtn = true;
                      });
                    }
                  }
                  return false;
                },
                child:
                    CustomScrollView(controller: _scrollController, slivers: [
                  SliverToBoxAdapter(
                    child: AspectRatio(
                      aspectRatio: 1,
                      child: Swiper(
                        itemBuilder: (BuildContext context, int index) {
                          return MyImage(
                              imgSrc: json
                                  .decode(this.product['sliderImage'])[index]);
                        },
                        autoplay: false,
                        itemCount:
                            json.decode(this.product['sliderImage']).length,
                        pagination: SwiperPagination(
                            builder: ProductContentPageIndicator(
                                color: Colors.green),
                            alignment: Alignment.bottomRight),
                      ),
                    ),
                  ),

                  SliverToBoxAdapter(
                    child: Product(
                        key: globalKeySp,
                        product: this.product,
                        productValue: this.productValue),
                  ),
                      SliverToBoxAdapter(
                        child: SizedBox(height:20.w),
                      ),
                  SliverToBoxAdapter(
                    child: Comment(
                      key: globalKeyPj,
                    ),
                  ),
                      SliverToBoxAdapter(
                        child: SizedBox(height:20.w),
                      ),
                  SliverToBoxAdapter(
                    child: Recommend(
                        key: globalKeyTj,
                        recommendProducts: this.recommendProducts),
                  ),
                  SliverToBoxAdapter(
                    child: Description(
                        key: globalKeyXq, description: this.description),
                  ),
                ]),
              ),
            ),
            ProductBottom(productValue: productValue)
          ],
        ),
        floatingActionButton: !showToTopBtn
            ? null
            : FloatingActionButton(
                onPressed: () {
                  //返回到顶部时执行动画
                  _scrollController.animateTo(.0,
                      duration: Duration(milliseconds: 300),
                      curve: Curves.ease);
                },
                child: Icon(Icons.arrow_upward),
              ),
      );
    } else {
      return Scaffold(
        body: MyLoadding(),
      );
    }
  }
}
